from typing import Generic, Optional, TypeVar, Any
from pydantic import BaseModel, Field


T = TypeVar("T")


class ApiResponse(BaseModel, Generic[T]):
    """统一的接口返回模型

    约定返回结构：
    {
        "code": 200,
        "msg": "登录成功",
        "data": {}
    }
    """

    code: int = Field(200, description="业务状态码")
    msg: str = Field("成功", description="提示信息")
    data: Optional[T] = Field(None, description="数据载体")


def api_success(data: Optional[T] = None, msg: str = "成功", code: int = 200) -> ApiResponse[T]:
    """构造成功响应"""
    return ApiResponse(code=code, msg=msg, data=data)


def api_error(msg: str, code: int = 400, data: Optional[Any] = None) -> ApiResponse[Any]:
    """构造失败响应（不抛出 HTTP 异常，统一返回结构）"""
    return ApiResponse(code=code, msg=msg, data=data)